/*
 * CopyRight(C) Kenbin
 */

#include "lws_utils.h"

int LWS::GB2312HanziIndex(string &str)
{
    if(str.size() < 2) {
	return -1;
    }

    return ((unsigned char)str[0] - 176) * 94 + (unsigned char)str[1] - 161;
}

bool LWS::IsGB2312Hanzi(string &str)
{
    if(str.size() < 2) {
	return false;
    }

    int idx = GB2312HanziIndex(str);
    if(idx >= 0 && idx < 6768) {
	return true;
    } else {
	return false;
    }
}

bool LWS::IsGB2312HanziS(string &str)
{
    if(str.size() % 2 != 0) {
	return false;
    }

    for(unsigned i = 0; i < str.size()-1; i = i+2)
    {
	string S = str.substr(i, 2);
	if(!IsGB2312Hanzi(S)) {
	    return false;
	}
    }

    return true;
}

string LWS::NextCHAR(const string &str, int cur_pos)
{
    if(str.size() < cur_pos + 1) {
	return "";
    }

    if(str.at(cur_pos) < 0) { /* maybe GB2312, GBK */
	return str.substr(cur_pos, 2);
    } else { /* ASCII */
	return str.substr(cur_pos, 1);
    }
}

int LWS::CHARCount(const string &str)
{
    int count = 0;
    for(unsigned i = 0; i < str.size(); ++ i, ++ count)
    {
	if(str[i] < 0) { /* maybe GB2312, GBK */
	    ++i;
	}
    }

    return count;
}

void LWS::Parse(const string &str, vector<string> &items, const char separator)
{
    items.clear();

    string::size_type P1 = 0, P2 = 0;
    string item;

    while((P2 = str.find_first_of(separator, P1)) != string::npos)
    {
	item = str.substr(P1, P2-P1);
	P1 = P2 + 1;
	if(!item.empty()) {
	    items.push_back(item);
	}
    }

    item = str.substr(P1);
    if(!item.empty()) {
	items.push_back(item);
    }
}

void LWS::Parse(const string &str, pair<string, string> &item, const char separator)
{
    string::size_type P;

    P = str.find_first_of(separator, 0);
    item.first = str.substr(0, P);
    if(P != string::npos) {
	item.second = str.substr(P+1);
    } else {
	item.second = "";
    }
}

void LWS::Parse(const string &str, vector<pair<string, string> > &items)
{
    items.clear();

    vector<string> itms;
    Parse(str, itms);

    for(unsigned i = 0; i < itms.size(); ++ i)
    {
	pair<string, string> item;
	Parse(itms[i], item);
	items.push_back(item);
    }
}
